using LiJ.Common.Core;
using LiJ.Common.Core.Enums;
using LiJ.Framework.Msg.Mos;
using System;
using System.Collections.Concurrent;

namespace LiJ.Framework.Msg
{
	/// <summary>
	///  用户自定义消息处理句柄
	/// </summary>
	public static class WxMsgConfigProvider
	{
		private static readonly ConcurrentDictionary<string, WxMsgProcessor> processorDirs = new ConcurrentDictionary<string, WxMsgProcessor>();

		/// <summary>
		/// 默认的配置AppKey信息
		/// </summary>
		public static WxMsgConfig DefaultConfig
		{
			get;
			set;
		}

		/// <summary>
		///   当前模块名称
		/// </summary>
		public static string ModuleName
		{
			get;
			set;
		} = "social_center";


		/// <summary>
		/// 注册消息处理委托
		/// </summary>
		/// <param name="msgType">消息类型</param>
		/// <param name="func"></param>
		public static ResultMo RegisteProcessor<TRecMsg>(string msgType, Func<TRecMsg, WxBaseReplyMsg> func) where TRecMsg : WxBaseRecMsg, new()
		{
			string key = msgType.ToLower();
			if (WxMsgConfigProvider.processorDirs.ContainsKey(key))
			{
				return new ResultMo(ResultTypes.ObjectExsit, "已存在相同的消息处理类型！");
			}
			WxMsgProcessor<TRecMsg> value = new WxMsgProcessor<TRecMsg>
			{
				ProcessFunc = func
			};
			if (!WxMsgConfigProvider.processorDirs.TryAdd(key, (WxMsgProcessor)value))
			{
				return new ResultMo(ResultTypes.ObjectExsit, "注册消息处理句柄失败！");
			}
			return new ResultMo();
		}

		/// <summary>
		/// 注册事件消息处理委托
		/// </summary>
		/// <param name="eventName">事件名称</param>
		/// <param name="func"></param>
		public static ResultMo RegisteEventProcessor<TRecMsg>(string eventName, Func<TRecMsg, WxBaseReplyMsg> func) where TRecMsg : WxBaseRecEventMsg, new()
		{
			return WxMsgConfigProvider.RegisteProcessor("event_" + eventName, func);
		}

		/// <summary>
		///  获取自定义的句柄
		/// </summary>
		/// <param name="name"></param>
		/// <returns></returns>
		internal static WxMsgProcessor GetProcessor(string name)
		{
			WxMsgProcessor result = default(WxMsgProcessor);
			WxMsgConfigProvider.processorDirs.TryGetValue(name, out result);
			return result;
		}

		/// <summary>
		///  设置上下文配置信息
		/// </summary>
		/// <param name="config"></param>
		public static void SetContextConfig(WxMsgConfig config)
		{
			BaseConfigProvider<WxMsgConfig, WxMsgBaseHandler>.SetContextConfig(config);
		}
	}
}
